<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="http://plugins.jquery.com/files/jquery.cookie.js.txt"></script>
<form method="POST" onsubmit="return checkData();">
    <dl>
        <dt><button onclick="reload(); return false">讀取前次資料</button></dt>
        <dd>&nbsp;</dd>

        <dt>姓名</dt>
        <dd><input class="cookie" name="builder_name" style="width:50%;"/></dd>
        <dd>&nbsp;</dd>

        <dt>喜愛運動</dt>
        <dd>
            <select class="cookie" name="status">
                <option value="0" selected>否</option>
                <option value="1">是</option>
            </select>
        </dd>
        <dd>&nbsp;</dd>

        <dt>狀態</dt>
        <dd><input type="checkbox" name="status"/> 已婚</dd>
        <dd>&nbsp;</dd>
        <dd>&nbsp;</dd>

        <dt><button type="submit">執行</button></dt>

    </dl>
</form>

<script type="text/javascript">

function checkData()
{
    // ... do check ...

    // ... do save ...
    save();

    return true;
}

function save()
{
    $( '.cookie' ).each( function(){
        var target_cookie = '__' + $(this).attr('name');
        var data = $(this).val();
        if( $(this).attr('type') == 'checkbox' )
            data = $(this).is(':checked') ? 'on' : 'off';
    
        $.cookie( target_cookie, data , { path: '/', expires: 365 } );
        //console.log( target_cookie +' : ' + $(this).attr('type') + ' : ' + $.cookie( target_cookie ) + ' : ' + data );
    });
}

function reload()
{
    $( '.cookie' ).each( function(){
        var target_cookie = '__' + $(this).attr('name');
        if( $.cookie( target_cookie ) )
        {
            if( $(this).attr('type') == 'checkbox' )
            {
                if( $.cookie( target_cookie ) == 'on' )
                    $(this).attr('checked', true);
                else
                    $(this).attr('checked', false);
            }
            else if( $(this).attr('type') == 'select-one' && $(this).get(0) && $(this).get(0).options && $(this).get(0).options.length )
            {
                var data = $.cookie( target_cookie );
                var options_list = $(this).get(0).options;
                for( var i=0 , cnt = options_list.length ; i<cnt ; ++i )
                {
                    if( options_list[i].value == data )
                    {
                        $( options_list[i] ).attr( 'selected' , 'selected' );
                        break;
                    }
                }
                $(this).trigger('change');  // 有些 select 可以搭配 change 事件
            }
            else
                $(this).val( $.cookie( target_cookie ) );
            //console.log( target_cookie +' : ' + $(this).attr('type') + ' : ' + $.cookie( target_cookie ) );
        }
    });
}
</script>
